package com.example.vote.controller;

import com.example.vote.entity.User;
import com.example.vote.entity.Vote;
import com.example.vote.mapper.VoteMapper;

import com.example.vote.service.BizException;
import com.example.vote.service.IVoteService;
import com.example.vote.vo.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 投票系统-题目表-2 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/vote/vote")
public class VoteController {

    @Resource
    VoteMapper voteMapper;

    @RequestMapping("query")
    public Map<String, Object> query(String vname,
                            @RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "5") int size) {
       // Page<Vote> p = new Page<>(page, size);
        //PageHelper   必须在查询方法前一行代码执行分页代码设置
        Page<Object> p = PageHelper.startPage(page, size);
        //pageHelper 通过插件在后台直接获取到数据 设置到p 中
        List<Vote> votes = voteMapper.selectLikeVname(vname);
        Map<String, Object> res = new HashMap<>();
        res.put("total", p.getTotal());
        res.put("rows",p);
        return  res;
    }

    @Resource
    IVoteService voteService;
    @RequestMapping("create")
    public Result create(@RequestBody Vote vote,
                         @SessionAttribute User loginedUser)
            //  BizException  在哪捕获
            throws BizException {
        //设置用户id
        vote.setUsid(loginedUser.getId());
        voteService.create(vote);
        return new Result(1,"添加投票成功",vote);

    }


    @RequestMapping("find")
    public Vote find(int id) {

        return  voteMapper.selectById(id);
    }

    @RequestMapping("del")
    public Result delById(HttpServletRequest request, int id) throws BizException, NoSuchFieldException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginedUser");
        if(user == null){
            throw new BizException("请先登录");
        }
        String name =  user.getUname();

        voteService.delById(id,name);
        return new Result(1,"删除投票成功",null);

    }

}
